import base64

import pyaudio
import wave

import requests

chunk = 1024
format = pyaudio.paInt16
channels = 1
rate = 8000
record_seconds = 5
wave_output_filename = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format=format,
                channels=channels,
                rate=rate,
                input=True,
                frames_per_buffer=chunk)
frames = []
print("Recording...")
for i in range(int(rate / chunk * record_seconds)):
    data = stream.read(chunk)
    frames.append(data)
print("Finished recording.")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(wave_output_filename, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(p.get_sample_size(format))
wf.setframerate(rate)
wf.writeframes(b''.join(frames))
wf.close()

with open("output.wav", "rb") as file:
    data = file.read()
    file.close()
    url = "http://ability.ai.rmd.com.cn/book/search"
    #url = "http://localhost:8080/book/search"
    myParams = {"robotId": 6, "fs": 8000, "cid": "test01","userLimit":5, "audioData": base64.b64encode(data)}
    res = requests.post(url=url, json=myParams)

    print('url:', res.request.url)  # 查看发送的url
    print("response:", res.text)  # 返回请求结果